<?php
/****
分页类:
总条数    $total
每页条数  $perpage
当前页    $page
***/

defined('JSJZJX')||exit('非法访问！');

class PageTool {
    protected $total = 0;
    protected $perpage = 10;
    protected $page = 9;
    

    public function __construct($total,$page=false,$perpage=false) {
        $this->total = $total;
        if($perpage) {
            $this->perpage = $perpage;
        }

        if($page) {
            $this->page = $page;
        }
    }


    // 主要函数,创建分页导航
    public function show() {

        $cnt = ceil($this->total/$this->perpage);  // 得到总页数
        $prev = $this->page-1;
        $next = $this->page+1;
        if($prev<1){
           $prev=1;
        }
        if($next>$cnt){
            $next=$cnt;
        }

        $uri = $_SERVER['REQUEST_URI'];

        $parse = parse_url($uri);
        


        $param = array();
        if(isset($parse['query'])) {
            parse_str($parse['query'],$param);
        }

        // 不管$param数组里,有没有page单元,都unset一下,确保没有page单元,
        // 即保存除page之外的所有单元
        unset($param['page']);
        
        $url = $parse['path'] . '?';
        if(!empty($param)) {
            $param = http_build_query($param);
            $url = $url . $param . '&';
        }
              
        // 下一个关键,就是计算页码导航
        $nav = array();
        $nav[0] = '<li class="active"><span>' . $this->page . '</span></li>';
              
        for($left = $this->page-1,$right=$this->page+1;($left>=1||$right<=$cnt)&&count($nav) <= 5;) {
            
            if($left >= 1) {
                array_unshift($nav,'<li><a href="' . $url . 'page=' . $left . '">&nbsp;' . $left . '&nbsp;</a><li>');
                $left -= 1;
            }
            
            if($right <= $cnt) {
                array_push($nav,'<li><a href="' . $url . 'page=' . $right . '">&nbsp;' . $right . '&nbsp;</a></li>');
                $right += 1;
            }
        }
        
        array_unshift($nav,'<li><a href="' . $url . 'page=' . $prev . '"" >上一页</a></li>');
        array_unshift($nav,'<li><a href="' . $url . 'page=1">首页</a></li>');
        array_push($nav, '<li><a href="' . $url . 'page=' . $next . '">下一页</a></li>') ;     
        array_push($nav, '<li><a href="' . $url . 'page=' . $cnt . '">末页</a></li>') ;        
         
        return implode('',$nav);

    }

}



